package top.xiaoshuaila.searescue.service;

import com.alibaba.fastjson.JSONObject;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xiaoshuaila.searescue.pojo.Serial;
import top.xiaoshuaila.searescue.serialport.manager.SerialPortManager;
import top.xiaoshuaila.searescue.serialport.utils.ByteUtils;
import top.xiaoshuaila.searescue.serialport.utils.ShowUtils;

import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Arrays;

@Service
public class SerialPortservice {
    @Autowired
    private Serial serial;
    @Autowired
    private DataDeal dataDeal;


    public ArrayList<String> findPorts(){
        return SerialPortManager.findPorts();
    }
    /*保存串口信息*/
    public boolean save(Serial ser){
        System.out.println(ser);
        serial.setPort(ser.getPort());
        serial.setBotelv(ser.getBotelv());
        serial.setTingzhiwei(ser.getTingzhiwei());
        serial.setJiaoyanwei(ser.getJiaoyanwei());
        serial.setType(ser.getType());
        System.out.println(serial);
        return true;
    }
    /*打开串口*/
    public String OpenSerial(Serial ser){
        String[] msg=new String[]{"开启成功"};
        System.out.println(ser);
        serial.setPort(ser.getPort());
        serial.setBotelv(ser.getBotelv());
        serial.setTingzhiwei(ser.getTingzhiwei());
        serial.setJiaoyanwei(ser.getJiaoyanwei());
        serial.setType(ser.getType());
        System.out.println(serial);
        if (!serial.isIsopen() && serial.getSerialPort() == null) {
            closeSerialPort();
            openSerialPort(msg);
        } else {
            closeSerialPort();
        }
        return msg[0];
    }
    /*发送数据*/
    public void send(String data){
        sendData(data);
    }
    /*打开串口*/
    public void openSerialPort(String[] msg ) {
        // 获取串口名称
        String commName = serial.getPort();
        // 获取波特率，默认为115200
        int baudrate = serial.getBotelv();

        // 检查串口名称是否获取正确
        if (commName == null || commName.equals("")) {
            msg[0] ="没有搜索到有效串口！";
            return;
        } else {
            try {
                serial.setSerialPort(SerialPortManager.openPort(commName, baudrate));
                if (serial.getSerialPort() != null) {
                    serial.setIsopen(true);
                }
            } catch (PortInUseException e) {
                msg[0] ="串口已被占用!";
                return;
            }
        }

        // 添加串口监听
        SerialPortManager.addListener(serial.getSerialPort(), new SerialPortManager.DataAvailableListener() {

            @Override
            public void dataAvailable() {
                byte[] data = null;
                try {
                    if (serial.getSerialPort() == null) {
                        msg[0] ="串口对象为空，监听失败！";
                        return;
                    } else {
                        // 读取串口数据
                        data = SerialPortManager.readFromPort(serial.getSerialPort());

                        // 以字符串的形式接收数据
                        if (serial.getType()==0) {
                            String str=new String(data);
                            if(str.startsWith("$BOAT")){
                                dataDeal.HTSStatus(str);
                            }
                            else if (str.startsWith("$TAG")){
                                dataDeal.TTSStatus(str);
                            }
                            else
                            {
                                dataDeal.other(str);
                            }
                        }

                        // 以十六进制的形式接收数据
                        if (serial.getType()==1) {
                            System.out.println(ByteUtils.byteArrayToHexString(data));
                        }
                    }
                } catch (Exception e) {
                    ShowUtils.errorMessage(e.toString());
                    // 发生读取错误时显示错误信息后退出系统
                    closeSerialPort();
                    msg[0]="连接失败";
                    throw new RuntimeException("以撒的");
                }
            }
        });
    }
    /*关闭串口*/
    public void closeSerialPort() {
        SerialPortManager.closePort(serial.getSerialPort());
        serial.setIsopen(false);
        serial.setSerialPort(null);
    }
    /*发送消息*/
    public void sendData(String data) {
        // 待发送数据
        data = data;
        System.out.println(data);
        if (serial.getSerialPort() == null) {
            ShowUtils.warningMessage("请先打开串口！");
            return;
        }
        if ("".equals(data) || data == null) {
            ShowUtils.warningMessage("请输入要发送的数据！");
            return;
        }
        // 以字符串的形式发送数据
        if (serial.getType()==0) {
            SerialPortManager.sendToPort(serial.getSerialPort(), (data+"\r\n").getBytes());
        }
        // 以十六进制的形式发送数据
        if (serial.getType()==1) {
            SerialPortManager.sendToPort(serial.getSerialPort(), ByteUtils.hexStr2Byte(data));
        }
    }


}
